<template>
  <div class="database-configs">
    <!-- 添加/编辑配置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加数据库配置' : '编辑数据库配置'"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="configForm"
        :rules="formRules"
        label-width="140px"
      >
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="configForm.name" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="数据库类型" prop="db_type">
          <el-select v-model="configForm.db_type" placeholder="请选择数据库类型" style="width: 100%">
            <el-option label="Redis" value="redis" />
            <el-option label="StarRocks" value="starrocks" />
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
          </el-select>
        </el-form-item>
        <el-form-item label="主机地址" prop="host">
          <el-input v-model="configForm.host" placeholder="请输入主机地址" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input-number v-model="configForm.port" :min="1" :max="65535" style="width: 100%" />
        </el-form-item>
        <el-form-item label="数据库名" prop="database_name">
          <el-input v-model="configForm.database_name" placeholder="请输入数据库名" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="configForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="configForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="连接池大小" prop="connection_pool_size">
          <el-input-number v-model="configForm.connection_pool_size" :min="1" :max="100" style="width: 100%" />
        </el-form-item>
        <el-form-item label="连接超时(秒)" prop="connection_timeout">
          <el-input-number v-model="configForm.connection_timeout" :min="1" :max="300" style="width: 100%" />
        </el-form-item>
        <el-form-item label="读取超时(秒)" prop="read_timeout">
          <el-input-number v-model="configForm.read_timeout" :min="1" :max="300" style="width: 100%" />
        </el-form-item>
        <el-form-item label="写入超时(秒)" prop="write_timeout">
          <el-input-number v-model="configForm.write_timeout" :min="1" :max="300" style="width: 100%" />
        </el-form-item>
        <el-form-item label="启用SSL" prop="ssl_enabled">
          <el-switch v-model="configForm.ssl_enabled" />
        </el-form-item>
        <el-form-item label="设为默认" prop="is_default">
          <el-switch v-model="configForm.is_default" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="configForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-card>
      <!-- 搜索和筛选 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="filters.search"
              placeholder="搜索配置名称或描述"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="filters.dbType" placeholder="数据库类型" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="Redis" value="redis" />
              <el-option label="StarRocks" value="starrocks" />
              <el-option label="MySQL" value="mysql" />
              <el-option label="PostgreSQL" value="postgresql" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="filters.status" placeholder="状态" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="启用" value="true" />
              <el-option label="禁用" value="false" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="filters.isDefault" placeholder="默认配置" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="是" value="true" />
              <el-option label="否" value="false" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleFilter">筛选</el-button>
            <el-button @click="clearFilters">清除</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 表格工具栏 -->
      <div class="table-toolbar">
        <div class="left">
          <el-button type="success" size="small" @click="handleBatchTest">批量测试</el-button>
          <el-button type="warning" size="small" @click="handleBatchEnable">批量启用</el-button>
        </div>
        <div class="right">
          <el-button type="primary" size="small" @click="showAddDialog">添加配置</el-button>
          <el-button size="small" @click="loadConfigs">刷新</el-button>
          <el-dropdown @command="handleColumnToggle">
            <el-button size="small">
              列设置 <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  v-for="col in availableColumns" 
                  :key="col.prop"
                  :command="col.prop"
                >
                  <el-checkbox 
                    v-model="col.visible" 
                    @change="toggleColumn(col.prop)"
                  >
                    {{ col.label }}
                  </el-checkbox>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      
      <el-table :data="configs" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="配置名称" />
        <el-table-column prop="db_type" label="数据库类型">
          <template #default="{ row }">
            <el-tag :type="getDbTypeColor(row.db_type)" size="small">
              {{ getDbTypeText(row.db_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="host" label="主机" />
        <el-table-column prop="port" label="端口" width="80" />
        <el-table-column prop="database_name" label="数据库名" />
        <el-table-column prop="is_default" label="默认配置" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.is_default" type="success" size="small">是</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <ActionMenu
              :actions="[
                { label: '测试连接', onClick: () => testConnection(row) },
                { label: '编辑', onClick: () => editConfig(row) },
                { label: row.is_active ? '禁用' : '启用', onClick: () => toggleConfig(row) },
                { label: '删除', onClick: () => deleteConfig(row) }
              ]"
              :primary-count="2"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { systemApi } from '@/api/system'
import type { DatabaseConfig } from '@/types'
import { Search, ArrowDown } from '@element-plus/icons-vue'
import ActionMenu from '@/components/ActionMenu.vue'

const configs = ref<DatabaseConfig[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()

// 表单数据
const configForm = ref<Partial<DatabaseConfig>>({
  name: '',
  db_type: 'redis',
  host: 'localhost',
  port: 6379,
  database_name: '',
  username: '',
  password: '',
  connection_pool_size: 20,
  connection_timeout: 30,
  read_timeout: 60,
  write_timeout: 60,
  ssl_enabled: false,
  description: '',
  is_default: false
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' }
  ],
  db_type: [
    { required: true, message: '请选择数据库类型', trigger: 'change' }
  ],
  host: [
    { required: true, message: '请输入主机地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入端口', trigger: 'blur' }
  ]
}

const loadConfigs = async () => {
  loading.value = true
  try {
    const response = await systemApi.getDatabaseConfigs()
    configs.value = response.data.items
  } catch (error) {
    console.error('Failed to load configs:', error)
    ElMessage.error('加载配置列表失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  dialogType.value = 'add'
  configForm.value = {
    name: '',
    db_type: 'redis',
    host: 'localhost',
    port: 6379,
    database_name: '',
    username: '',
    password: '',
    connection_pool_size: 20,
    connection_timeout: 30,
    read_timeout: 60,
    write_timeout: 60,
    ssl_enabled: false,
    description: '',
    is_default: false
  }
  dialogVisible.value = true
}

const editConfig = (config: DatabaseConfig) => {
  dialogType.value = 'edit'
  configForm.value = { ...config }
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await systemApi.createDatabaseConfig(configForm.value)
      ElMessage.success('添加成功')
    } else {
      await systemApi.updateDatabaseConfig(configForm.value.id!, configForm.value)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    loadConfigs()
  } catch (error) {
    console.error('Form submission failed:', error)
    ElMessage.error('操作失败')
  }
}

const testConnection = async (config: DatabaseConfig) => {
  try {
    const response = await systemApi.testDatabaseConnection(config.id)
    if (response.data.status === 'success') {
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error('连接测试失败')
    }
  } catch (error) {
    console.error('Test connection failed:', error)
    ElMessage.error('连接测试失败')
  }
}

const toggleConfig = async (config: DatabaseConfig) => {
  try {
    await systemApi.toggleDatabaseConfig(config.id, !config.is_active)
    ElMessage.success(config.is_active ? '禁用成功' : '启用成功')
    loadConfigs()
  } catch (error) {
    console.error('Toggle config failed:', error)
    ElMessage.error('操作失败')
  }
}

const deleteConfig = async (config: DatabaseConfig) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除配置 "${config.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await systemApi.deleteDatabaseConfig(config.id)
    ElMessage.success('删除成功')
    loadConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete failed:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleBatchTest = () => {
  ElMessage.info('批量测试功能开发中...')
}

const handleBatchEnable = () => {
  ElMessage.info('批量启用功能开发中...')
}

const getDbTypeColor = (type: string): string => {
  const colors: Record<string, string> = {
    'redis': 'danger',
    'starrocks': 'primary',
    'mysql': 'success',
    'postgresql': 'warning'
  }
  return colors[type] || 'info'
}

const getDbTypeText = (type: string): string => {
  const texts: Record<string, string> = {
    'redis': 'Redis',
    'starrocks': 'StarRocks',
    'mysql': 'MySQL',
    'postgresql': 'PostgreSQL'
  }
  return texts[type] || type
}

// 搜索和筛选
const filters = ref({
  search: '',
  dbType: '',
  status: '',
  isDefault: ''
})

const handleSearch = () => {
  loadConfigs()
}

const handleFilter = () => {
  loadConfigs()
}

const clearFilters = () => {
  filters.value = {
    search: '',
    dbType: '',
    status: '',
    isDefault: ''
  }
  loadConfigs()
}



// 列设置
const availableColumns = ref([
  { prop: 'name', label: '配置名称', visible: true },
  { prop: 'db_type', label: '数据库类型', visible: true },
  { prop: 'host', label: '主机', visible: true },
  { prop: 'port', label: '端口', visible: true },
  { prop: 'database_name', label: '数据库名', visible: true },
  { prop: 'is_default', label: '默认配置', visible: true },
  { prop: 'is_active', label: '状态', visible: true },
  { prop: 'description', label: '描述', visible: true }
])

const toggleColumn = (prop: string) => {
  const column = availableColumns.value.find(col => col.prop === prop)
  if (column) {
    column.visible = !column.visible
  }
}

const handleColumnToggle = (command: string) => {
  toggleColumn(command)
}

onMounted(() => {
  loadConfigs()
})
</script>

<style scoped>
.database-configs {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.left {
  display: flex;
  gap: 10px;
}

.right {
  display: flex;
  gap: 10px;
}
</style> 